package cn.omisheep.au.core;

import cn.omisheep.au.AuUserData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
@SuppressWarnings("all")
@Slf4j
public class AuFactory implements ApplicationContextAware {

    Map<String, AuUserData> userDatabaseMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AuUserData> map = applicationContext.getBeansOfType(AuUserData.class);
        for (Map.Entry<String, AuUserData> entry : map.entrySet()) {
            ParameterizedType parameterizedType = (ParameterizedType) entry.getValue().getClass().getGenericInterfaces()[0];
            Class<?> clz = (Class<?>) parameterizedType.getActualTypeArguments()[0];

            userDatabaseMap.put(clz.getName(), entry.getValue());
        }
    }


    public Object getUser(MethodParameter parameter, Claims claims) {
        if (claims == null) return null;
        return getUser(parameter.getParameterType(),
                claims.get("userId"),
                claims.getSubject(), claims);
    }

    public Object getUser(Class<?> clz, Object userId, String username, Claims claims) {
        AuUserData userData = userDatabaseMap.get(clz.getName());

        if (userData == null) return null;
        return userData.getUser(userId, username, claims);
    }

    public Object login(Class<?> clz, String username, String password) {
        AuUserData userData = userDatabaseMap.get(clz.getName());

        if (userData == null) return null;
        return userData.login(username, password);
    }


}
